extends CharacterBody2D

# 等级与经验
@export var starting_level: int = 1  # 初始等级
var current_level: int
var current_exp: int = 0
var exp_to_next_level: int = 100  # 升级所需经验

# 角色属性 (基础值，随等级提升)
@export var base_max_hp: int = 100  # 基础最大血量
@export var base_max_mp: int = 50   # 基础最大灵力值
@export var base_strength: int = 5  # 基础力量(影响物理伤害)
@export var base_physique: int = 5  # 基础体魄(影响血量和防御)
@export var base_agility: int = 4   # 基础敏捷(影响速度和闪避)
@export var base_spirit: int = 3    # 基础精神(影响灵力和回复)
@export var base_luck: int = 2      # 基础幸运(影响暴击、掉落等)

# 当前状态
var current_hp: int
var current_mp: int  # 灵力值
var is_alive: bool = true
var strength: int
var physique: int
var agility: int
var spirit: int
var luck: int

# 信号(用于UI更新等)
signal hp_changed(current, max)
signal mp_changed(current, max)
signal exp_changed(current, required)
signal level_up(new_level)
signal attribute_changed()
signal character_died()

func _ready() -> void:
	# 初始化等级
	current_level = starting_level
	calculate_exp_requirement()
	
	# 初始化属性和状态
	update_attributes()
	current_hp = get_max_hp()
	current_mp = get_max_mp()
	
	$Button.pressed.connect(_on_button_pressed)
	add_to_group("roles")
	
	# 发送初始信号
	hp_changed.emit(current_hp, get_max_hp())
	mp_changed.emit(current_mp, get_max_mp())
	exp_changed.emit(current_exp, exp_to_next_level)

func _process(delta: float) -> void:
	if is_on_wall():
		print("碰到墙壁!")
	
	# 灵力自动回复（受精神属性影响）
	if is_alive and current_mp < get_max_mp():
		var mp_regen = spirit * 0.02 * delta
		current_mp = min(current_mp + mp_regen, get_max_mp())
		mp_changed.emit(current_mp, get_max_mp())

# 属性计算（带等级加成）
func update_attributes():
	# 每次升级获得的属性点
	var level_bonus = current_level - 1
	
	# 计算当前属性（基础值 + 等级加成）
	strength = base_strength + level_bonus * 2
	physique = base_physique + level_bonus * 2
	agility = base_agility + level_bonus * 2
	spirit = base_spirit + level_bonus  # 精神影响灵力
	luck = base_luck + level_bonus      # 幸运属性成长
	
	attribute_changed.emit()

# 计算升级所需经验
func calculate_exp_requirement():
	exp_to_next_level = int(100 * pow(1.2, current_level - 1))

# 获得经验值
func gain_exp(amount: int):
	if not is_alive:
		return
		
	current_exp += amount
	exp_changed.emit(current_exp, exp_to_next_level)
	
	# 检查是否升级
	while current_exp >= exp_to_next_level:
		level_up_process()

# 升级处理
func level_up_process():
	current_exp -= exp_to_next_level
	current_level += 1
	level_up.emit(current_level)
	print("升级了！当前等级: ", current_level)
	
	calculate_exp_requirement()
	update_attributes()
	
	# 升级恢复状态
	current_hp = get_max_hp()
	current_mp = get_max_mp()
	hp_changed.emit(current_hp, get_max_hp())
	mp_changed.emit(current_mp, get_max_mp())
	exp_changed.emit(current_exp, exp_to_next_level)

# 基础攻击（包含幸运带来的暴击效果）
func attack() -> int:
	if not is_alive:
		return 0
		
	# 基础伤害
	var base_damage = strength * 3 + current_level * 2
	
	# 幸运影响暴击率（1% + 幸运值*0.5%的暴击概率）
	var crit_chance = 0.01 + (luck * 0.005)
	var is_crit = randf() <= crit_chance
	
	# 暴击造成1.5倍伤害
	if is_crit:
		var crit_damage = base_damage * 1.5
		print("暴击！造成 ", crit_damage, " 点伤害 (幸运值: ", luck, ")")
		return crit_damage
	else:
		print("造成 ", base_damage, " 点伤害")
		return base_damage

# 消耗灵力的特殊攻击
func special_attack() -> int:
	# 检查是否可以释放（需足够灵力）
	var mp_cost = 10  # 消耗10点灵力
	if not is_alive or current_mp < mp_cost:
		print("灵力不足，无法释放特殊攻击")
		return 0
		
	# 消耗灵力
	current_mp -= mp_cost
	mp_changed.emit(current_mp, get_max_mp())
	
	# 特殊攻击伤害（受精神和力量影响）
	var damage = (strength + spirit) * 2 + current_level * 3
	print("特殊攻击！造成 ", damage, " 点伤害 (消耗灵力: ", mp_cost, ")")
	return damage

# 受到伤害
func take_damage(amount: int) -> void:
	if not is_alive:
		return
		
	# 敏捷和幸运影响闪避率
	var dodge_chance = (agility * 0.003) + (luck * 0.002)
	if randf() <= dodge_chance:
		print("闪避成功！")
		return
		
	# 计算实际伤害(考虑体魄防御)
	var defense = physique * 2 + current_level
	var actual_damage = max(1, amount - defense)
	current_hp -= actual_damage
	hp_changed.emit(current_hp, get_max_hp())
	
	if current_hp <= 0:
		die()

# 恢复血量
func heal(amount: int) -> void:
	if not is_alive:
		return
		
	current_hp = min(current_hp + amount, get_max_hp())
	hp_changed.emit(current_hp, get_max_hp())

# 恢复灵力
func restore_mp(amount: int) -> void:
	if not is_alive:
		return
		
	current_mp = min(current_mp + amount, get_max_mp())
	mp_changed.emit(current_mp, get_max_mp())

# 获取最大血量
func get_max_hp() -> int:
	return base_max_hp + physique * 10 + current_level * 15

# 获取最大灵力
func get_max_mp() -> int:
	return base_max_mp + spirit * 5 + current_level * 8

# 角色死亡
func die() -> void:
	is_alive = false
	velocity = Vector2.ZERO
	character_died.emit()
	print("角色死亡")

# 幸运属性应用：获取物品时的加成
func get_loot_bonus() -> float:
	return 1.0 + (luck * 0.05)

# 获取当前属性
func get_current_attributes() -> Dictionary:
	return {
		"level": current_level,
		"strength": strength,
		"physique": physique,
		"agility": agility,
		"spirit": spirit,
		"luck": luck,
		"max_hp": get_max_hp(),
		"current_hp": current_hp,
		"max_mp": get_max_mp(),
		"current_mp": current_mp,
		"crit_chance": 0.01 + (luck * 0.005),
		"dodge_chance": (agility * 0.003) + (luck * 0.002)
	}

func _on_button_pressed():
	Event.emit_signal("open_role_detail", 'zsf')
	print("打开角色详情")
